package org.jeecg.modules.energyMeterMapping.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.energyMeterMapping.entity.EnergyMeterMapping;
import org.jeecg.modules.energyMeterMapping.entity.Tree;
import org.jeecg.modules.energyMeterMapping.service.IEnergyMeterMappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 电表映射
 * @Author: jeecg-boot
 * @Date:   2023-10-23
 * @Version: V1.0
 */
@Api(tags="电表映射")
@RestController
@RequestMapping("/energyMeterMapping/energyMeterMapping")
@Slf4j
public class EnergyMeterMappingController extends JeecgController<EnergyMeterMapping, IEnergyMeterMappingService> {
	@Autowired
	private IEnergyMeterMappingService energyMeterMappingService;
	
	/**
	 * 分页列表查询
	 *
	 * @param energyMeterMapping
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "电表映射-分页列表查询")
	@ApiOperation(value="电表映射-分页列表查询", notes="电表映射-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(EnergyMeterMapping energyMeterMapping,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<EnergyMeterMapping> queryWrapper = QueryGenerator.initQueryWrapper(energyMeterMapping, req.getParameterMap());
		Page<EnergyMeterMapping> page = new Page<EnergyMeterMapping>(pageNo, pageSize);
		IPage<EnergyMeterMapping> pageList = energyMeterMappingService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@GetMapping("/getPointByProductionLine")
	public Result<?> getPointByProductionLine(@RequestParam String productionLine){
		LambdaQueryWrapper<EnergyMeterMapping> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(EnergyMeterMapping::getProductionLine, productionLine);
		List<EnergyMeterMapping> list = energyMeterMappingService.list(wrapper);
		return Result.OK(list);
	}

	@GetMapping("/getTreeData")
	public Result<?> getTreeData(){
		List<EnergyMeterMapping> list = energyMeterMappingService.list();
		// 转换为treeData格式
		List<Tree> treeData = convertToTreeData(list);
		return Result.OK(treeData);
	}

	@GetMapping("/getAll")
	public Result<?> getAll(){
		List<EnergyMeterMapping> list = energyMeterMappingService.list();
		return Result.OK(list);
	}

	/**
	 *   添加
	 *
	 * @param energyMeterMapping
	 * @return
	 */
	@AutoLog(value = "电表映射-添加")
	@ApiOperation(value="电表映射-添加", notes="电表映射-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody EnergyMeterMapping energyMeterMapping) {
		LambdaQueryWrapper<EnergyMeterMapping> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(EnergyMeterMapping::getPoint, energyMeterMapping.getPoint());
		List<EnergyMeterMapping> list = energyMeterMappingService.list(wrapper);
		if (!(list == null || list.isEmpty())){
			throw new JeecgBootException("点位名称已存在！");
		}
		energyMeterMappingService.save(energyMeterMapping);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param energyMeterMapping
	 * @return
	 */
	@AutoLog(value = "电表映射-编辑")
	@ApiOperation(value="电表映射-编辑", notes="电表映射-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody EnergyMeterMapping energyMeterMapping) {
		LambdaQueryWrapper<EnergyMeterMapping> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(EnergyMeterMapping::getPoint, energyMeterMapping.getPoint());
		wrapper.ne(EnergyMeterMapping::getId, energyMeterMapping.getId());
		List<EnergyMeterMapping> list = energyMeterMappingService.list(wrapper);
		if (!(list == null || list.isEmpty())){
			throw new JeecgBootException("点位名称已存在！");
		}
		energyMeterMappingService.updateById(energyMeterMapping);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "电表映射-通过id删除")
	@ApiOperation(value="电表映射-通过id删除", notes="电表映射-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		energyMeterMappingService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "电表映射-批量删除")
	@ApiOperation(value="电表映射-批量删除", notes="电表映射-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.energyMeterMappingService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "电表映射-通过id查询")
	@ApiOperation(value="电表映射-通过id查询", notes="电表映射-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		EnergyMeterMapping energyMeterMapping = energyMeterMappingService.getById(id);
		if(energyMeterMapping==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(energyMeterMapping);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param energyMeterMapping
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, EnergyMeterMapping energyMeterMapping) {
        return super.exportXls(request, energyMeterMapping, EnergyMeterMapping.class, "电表映射");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, EnergyMeterMapping.class);
    }


	private List<Tree> convertToTreeData(List<EnergyMeterMapping> list) {
		// 创建一个空的treeData列表，用于存储转换后的结果
		List<Tree> treeData = new ArrayList<>();

		// 创建两个Map对象，用于存储不同层级的数据
		Map<String, List<Tree>> productMap = new HashMap<>();
		Map<String, List<Tree>> productionLineMap = new HashMap<>();

		// 遍历原始数据
		for (EnergyMeterMapping item : list) {
			// 获取数据项中的部门、产品、生产线和点位信息
			String dept = item.getDept();
			String product = item.getProduct();
			String productionLine = item.getProductionLine();
			String point = item.getPoint();

			// 创建点位节点
			Tree pointNode = new Tree();
			pointNode.setTitle(point);
			pointNode.setValue(point);
			pointNode.setKey(point);

			// 将点位节点添加到生产线Map中
			List<Tree> productionLineChildren = productionLineMap.getOrDefault(product, new ArrayList<>());
			productionLineChildren.add(pointNode);
			productionLineMap.put(product, productionLineChildren);

			// 将生产线Map添加到产品Map中
			List<Tree> productChildren = productMap.getOrDefault(dept, new ArrayList<>());
			Tree productionLineNode = new Tree();
			productionLineNode.setTitle(productionLine);
			productionLineNode.setValue(productionLine);
			productionLineNode.setKey(productionLine);
			productionLineNode.setChildren(productionLineMap.get(product));
			productChildren.add(productionLineNode);
			productMap.put(dept, productChildren);
		}

		// 将产品Map中的数据转换为treeData格式，并添加到treeData列表中
		for (Map.Entry<String, List<Tree>> productEntry : productMap.entrySet()) {
			String dept = productEntry.getKey();
			List<Tree> productChildren = productEntry.getValue();

			// 创建部门节点，并将产品节点作为其子节点
			Tree deptNode = new Tree();
			deptNode.setTitle(dept);
			deptNode.setValue(dept);
			deptNode.setKey(dept);
			deptNode.setChildren(productChildren);

			treeData.add(deptNode);
		}

		// 返回转换后的treeData结果
		return treeData;
	}
}
